package models

import (
	"fmt"
	"tms-server/driver"
	"tms-server/env"
)

type User struct {
	Id     int64  `xorm:"pk autoincr int(11)"`
	Uname  string `xorm:"unique varchar(50)"`
	Phone  string `xorm:"varchar(20)"`
	Pwd    string `xorm:"varchar(50)"`
	Empid  int    `xorm:"int(11)"`
	Perms  string `xorm:"varchar(50)"`
	Status string `xorm:"varchar(2)"`
}

type UserEmployee struct {
	User     `xorm:"extends"`
	Employee `xorm:"extends"`
}

func (UserEmployee) TableName() string {
	return DBUser
}

func FindUsers(start, limit int) (users []*UserEmployee, err error) {
	users = make([]*UserEmployee, 0)
	err = driver.X.
		Asc(DBUser+".id").
		Limit(limit, start).
		Join("LEFT", DBEmployee, fmt.Sprintf("%s.empid = %s.id", DBUser, DBEmployee)).
		Find(&users)
	if err != nil {
		return nil, err
	}
	return
}

func FindUserByID(id int64) (user *UserEmployee, err error) {
	user = new(UserEmployee)
	user.User.Id = id
	found, err := driver.X.
		Join("LEFT", DBEmployee, fmt.Sprintf("%s.empid = %s.id", DBUser, DBEmployee)).
		Get(user)
	if err != nil {
		return nil, err
	}
	if !found {
		return nil, env.NotFound
	}
	return
}

func FindUserByName(uname string) (user *UserEmployee, err error) {
	user = new(UserEmployee)
	user.Uname = uname
	found, err := driver.X.
		Join("LEFT", DBEmployee, fmt.Sprintf("%s.empid = %s.id", DBUser, DBEmployee)).
		Get(user)
	if err != nil {
		return nil, err
	}
	if !found {
		return nil, env.NotFound
	}
	return
}

func (userEmplyee *UserEmployee) GenResponse() map[string]interface{} {
	return map[string]interface{}{
		"id":       userEmplyee.User.Id,
		"uname":    userEmplyee.Uname,
		"phone":    userEmplyee.Employee.Phone,
		"empId":    userEmplyee.Empid,
		"perms":    userEmplyee.Perms,
		"status":   userEmplyee.User.Status,
		"name":     userEmplyee.Name,
		"position": userEmplyee.Position,
	}
}

func (user *User) Create(openID string) (err error) {

	return
}

func (user *User) Update(openID string) (err error) {

	return
}
